package com.kaigejava.demo.business.service.grab;

import cn.hutool.core.bean.BeanUtil;
import com.kaigejava.demo.business.barrgelog.dto.DanMuMsgDTO;
import com.kaigejava.demo.business.barrgelog.service.IBarrageLogService;
import com.kaigejava.demo.business.enums.TypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tech.ordinaryroad.live.chat.client.bilibili.msg.DanmuMsgMsg;
import tech.ordinaryroad.live.chat.client.commons.base.msg.BaseCmdMsg;
import tech.ordinaryroad.live.chat.client.commons.base.msg.BaseMsg;
import tech.ordinaryroad.live.chat.client.commons.base.msg.IMsg;
import tech.ordinaryroad.live.chat.client.douyu.client.DouyuLiveChatClient;
import tech.ordinaryroad.live.chat.client.douyu.config.DouyuLiveChatClientConfig;
import tech.ordinaryroad.live.chat.client.douyu.constant.DouyuCmdEnum;
import tech.ordinaryroad.live.chat.client.douyu.listener.IDouyuConnectionListener;
import tech.ordinaryroad.live.chat.client.douyu.listener.IDouyuMsgListener;
import tech.ordinaryroad.live.chat.client.douyu.msg.ChatmsgMsg;
import tech.ordinaryroad.live.chat.client.douyu.msg.DgbMsg;
import tech.ordinaryroad.live.chat.client.douyu.netty.handler.DouyuBinaryFrameHandler;
import tech.ordinaryroad.live.chat.client.douyu.netty.handler.DouyuConnectionHandler;

import javax.annotation.Resource;

/**
 * @BelongsProject: douyin-live-java
 * @Author: kaigejava
 * @CreateTime: 2023-11-09  17:22
 * @Description: 斗鱼直播
 * @Version: 1.0
 */
@Service
@Slf4j
public class DouYuGrabService extends BaseSendMessageService implements IGrabService{
    static Object lock = new Object();
    DouyuLiveChatClient client;
    @Resource
    private IBarrageLogService barrageLogService;
    @Override
    public void grab(String roomId,long timestamp) throws Exception {

        DouyuLiveChatClientConfig config = DouyuLiveChatClientConfig.builder()
                // TODO 修改房间id（支持短id）
                .roomId(Long.valueOf(roomId))
                .build();

        client = new DouyuLiveChatClient(config, new IDouyuMsgListener() {
            @Override
            public void onMsg(DouyuBinaryFrameHandler binaryFrameHandler, IMsg msg) {
                IDouyuMsgListener.super.onMsg(binaryFrameHandler, msg);
                // log.debug("{} 收到{}消息 {}", binaryFrameHandler.getRoomId(), msg.getClass(), msg);
            }

            @Override
            public void onDanmuMsg(DouyuBinaryFrameHandler binaryFrameHandler, ChatmsgMsg msg) {
                IDouyuMsgListener.super.onDanmuMsg(binaryFrameHandler, msg);

                //log.info("斗鱼系统的直播{} 收到弹幕 {}({})：{}", binaryFrameHandler.getRoomId(), msg.getUsername(), msg.getUid(), msg.getContent());
                //将弹幕发送到页面
                String message = "用户昵称【"+msg.getUsername()+"】"+",在【"+currentTime+"】的时候,发送的弹幕内容为:【"+msg.getContent()+"】";
                //入库保存
                DanMuMsgDTO danMuMsgDTO =  DanMuMsgDTO.douYUOf(msg,Long.parseLong(roomId));
                barrageLogService.save(danMuMsgDTO,TypeEnum.DYU_STATION.getCode());
                sendMessage(message, TypeEnum.DYU_STATION.getCode()+"_"+roomId+"_"+timestamp);
            }

            @Override
            public void onGiftMsg(DouyuBinaryFrameHandler binaryFrameHandler, DgbMsg msg) {
                IDouyuMsgListener.super.onGiftMsg(binaryFrameHandler, msg);

                //  log.info("{} 收到礼物 {}({}) {} {}({})x{}({})", binaryFrameHandler.getRoomId(), msg.getUsername(), msg.getUid(), "赠送", msg.getGiftName(), msg.getGiftId(), msg.getGiftCount(), msg.getGiftPrice());
            }

            @Override
            public void onCmdMsg(DouyuBinaryFrameHandler binaryFrameHandler, DouyuCmdEnum cmd, BaseCmdMsg<DouyuCmdEnum> cmdMsg) {
                IDouyuMsgListener.super.onCmdMsg(binaryFrameHandler, cmd, cmdMsg);

                // log.info("{} 收到CMD消息{} {}", binaryFrameHandler.getRoomId(), cmd, cmdMsg);
            }

            @Override
            public void onOtherCmdMsg(DouyuBinaryFrameHandler binaryFrameHandler, DouyuCmdEnum cmd, BaseCmdMsg<DouyuCmdEnum> cmdMsg) {
                IDouyuMsgListener.super.onOtherCmdMsg(binaryFrameHandler, cmd, cmdMsg);

                // log.debug("{} 收到其他CMD消息 {}", binaryFrameHandler.getRoomId(), cmd);
            }

            @Override
            public void onUnknownCmd(DouyuBinaryFrameHandler binaryFrameHandler, String cmdString, BaseMsg msg) {
                IDouyuMsgListener.super.onUnknownCmd(binaryFrameHandler, cmdString, msg);

                // log.debug("{} 收到未知CMD消息 {}", binaryFrameHandler.getRoomId(), cmdString);
            }
        }, new IDouyuConnectionListener() {
            @Override
            public void onConnected(DouyuConnectionHandler connectionHandler) {
                //log.info("{} onConnected", connectionHandler.getRoomId());
            }

            @Override
            public void onConnectFailed(DouyuConnectionHandler connectionHandler) {
                //log.info("{} onConnectFailed", connectionHandler.getRoomId());
            }

            @Override
            public void onDisconnected(DouyuConnectionHandler connectionHandler) {
                //log.info("{} onDisconnected", connectionHandler.getRoomId());
            }
        });
        client.connect();

        // 防止测试时直接退出
        while (true) {
            synchronized (lock) {
                lock.wait();
            }
        }
    }

    @Override
    public void close(String roomId) throws Exception {
        client.disconnect();
        boolean isShutdown = client.getWorkerGroup().isShutdown();
        if(!isShutdown){
            client.getWorkerGroup().shutdownGracefully();
            System.out.println("关闭【斗鱼】连接："+roomId);
        }
    }
}
